package com.gitee.ricesugar.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.gitee.ricesugar.controller.request.BaseRequest;
import com.gitee.ricesugar.entity.User;
import com.gitee.ricesugar.exception.ServiceException;
import com.gitee.ricesugar.mapper.UserMapper;
import com.gitee.ricesugar.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserService implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public void add(User obj) {
        this.checkUsernameExist(obj.getUsername());
        int uid = Math.abs(IdUtil.fastSimpleUUID().hashCode());
        obj.setUid(Integer.toString(uid));
        userMapper.add(obj);
    }

    @Override
    public void addList(User[] obj) {
        for(User user : obj){
            add(user);
        }
    }

    @Override
    public PageInfo<User> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<User> users = userMapper.listByCondition(baseRequest);
        for (User user : users) {
            int age = DateUtil.ageOfNow(user.getBirthday());
            user.setAge(age);
        }
        return new PageInfo<>(users);
    }

    @Override
    public User getByUid(String id) {
        User user = userMapper.getByUid(id);
        int age = DateUtil.ageOfNow(user.getBirthday());
        user.setAge(age);
        return user;
    }

    @Override
    public void checkUsernameExist(String username) {
        List<User> users = userMapper.listByUsername(username);
        if(!users.isEmpty()){
            throw new ServiceException("用户名已存在");
        }
    }

    @Override
    public void update(User obj) {
        Date date = new Date();
        obj.setUpdateDate(date);
        userMapper.updateByUid(obj);
    }

    @Override
    public void deleteByUid(String id) {
        userMapper.deleteByUid(id);
    }
}
